package com.example.demo.config;

import com.alibaba.fastjson.JSON;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.util.Arrays;
import java.util.Map;
import java.util.StringJoiner;

/**
 * https://blog.csdn.net/lmb55/article/details/82470388
 * https://blog.csdn.net/tianyaleixiaowu/article/details/70853147
 * https://blog.csdn.net/changerzhuo_319/article/details/96778859
 */
@Aspect
@Component
public class WebLogAcpect {

    private Logger logger = LoggerFactory.getLogger(WebLogAcpect.class);

    /**
     * 定义切入点，切入点为com.example.aop下的所有函数
     */
    @Pointcut("execution(public * com.example.demo.controller..*.*(..))")
    public void webLog(){}

    /**
     * 前置通知：在连接点之前执行的通知
     * @param joinPoint
     * @throws Throwable
     */
//    @Before("webLog()")
    public void doBefore(JoinPoint joinPoint) throws Throwable {
        // 接收到请求，记录请求内容
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        String requestURI = request.getRequestURI();
        StringBuilder sb =  new StringBuilder(300);
        sb.append("【");
        Object[] args = joinPoint.getArgs();
        String[] paramsName =  ((MethodSignature) joinPoint.getSignature()).getParameterNames();
        if(args != null && paramsName != null && args.length > 0 && paramsName.length > 0) {
            for (int i=0; i< paramsName.length; i++) {
                if (args[i] instanceof HttpServletResponse || args[i] instanceof HttpServletRequest) {
                    continue;
                }
                sb.append(paramsName[i]).append("=").append(JSON.toJSONString(args[i])).append(",");
            }
            sb.deleteCharAt(sb.length()-1);
        }
        sb.append("】");
        // 记录下请求内容
        logger.info("URL:{}, 入参:{}", request.getRequestURI(), sb.toString());
    }

    /**
     * 全局异常处理类全限定名
     */
    private static ThreadLocal<StringJoiner> threadLocal = new ThreadLocal<>();

    /**
     * 全局异常处理类全限定名
     */
    @Around("webLog()")
    public Object intoControllerLog(ProceedingJoinPoint point) throws Throwable {
        // 目标方法所在类全限定名
        String targetName = point.getSignature().getDeclaringType().getName();
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        String requestURI = request.getRequestURI();

        StringJoiner params = getParams(point);
        // 记录下请求内容，如果出现异常，会进入exceptionLog方法
        threadLocal.set(params);

        // 调用目标方法
        Object result = point.proceed();
        // 记录下返回内容
        saveLog(requestURI, params, result);
        threadLocal.remove();
        // 调用结果返回
        return result;
    }

    /**
     * 获取入参，参数对象如果没有用@Data注解或者实现toString方法，不能用Arrays.toString(point.getArgs())，此方法无法序列化对象
     * @param point
     * @return
     */
    private StringJoiner getParams(ProceedingJoinPoint point) {
        StringJoiner sb = new StringJoiner(",");

        // 目标方法签名
        Object[] args = point.getArgs();
        String[] paramsName = ((MethodSignature) point.getSignature()).getParameterNames();
        if (args != null && paramsName != null && args.length > 0 && paramsName.length > 0) {
            for (int i = 0; i < paramsName.length; i++) {
                if (args[i] instanceof HttpServletResponse || args[i] instanceof HttpServletRequest) {
                    continue;
                }
                String str = paramsName[i] + "=" + JSON.toJSONString(args[i]);
                sb.add(str);
            }
        }
        return sb;
    }

    @Pointcut("execution(public * com.example.demo.config.GlobalExceptionHandler.*(..))")
    public void exceptionLog(){}

    /**
     * 全局异常处理类全限定名
     */
    @Around("exceptionLog()")
    public Object exceptionLog(ProceedingJoinPoint point) throws Throwable {
        // 目标方法所在类全限定名
        String targetName = point.getSignature().getDeclaringType().getName();
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        String requestURI = request.getRequestURI();

        StringJoiner params = threadLocal.get();
        if (params == null) {
            // 当参数值异常时，比如整型复制ABC，不会进入controller
            // @Validated注解校验不通过，也不会进入controller
            params = new StringJoiner(",");
            params.add("请求参数格式不正确，未进入controller");
        }

        // 调用目标方法
        Object result = point.proceed();
        // 记录下返回内容
        saveLog(requestURI, params, result);
        threadLocal.remove();
        // 调用结果返回
        return result;
    }

    /**
     *
     * @param requestURI 请求URL
     * @param params 入参
     * @param returnVal 出参
     */
    private void saveLog(String requestURI, StringJoiner params, Object returnVal) {
        // 记录下返回内容
        logger.info("------------------------接口日志-----------------------" + "\n" +
                "URL:" + requestURI + "\n" +
                "接口参数:" + params.toString() + "\n" +
                "返回值:" + JSON.toJSONString(returnVal));
    }

//    @AfterReturning(returning = "ret",pointcut = "webLog()")
    public void doAfterReturning(Object ret) throws Throwable {
        // 处理完请求，返回内容
        logger.info("出参:{}", ret);
    }
}
